import { _decorator, AudioClip, AudioSource, Component, director, Node, resources } from 'cc';
import { Config } from './Config';
const { ccclass, property } = _decorator;

@ccclass('AudioManager')
export class AudioManager extends Component {
    private static _instance: AudioManager = null;

    private audioSource:AudioSource=null;
    /**
     * 获取实例
     */
    
    public static get Instance(): AudioManager {
        return this._instance;
    }
    protected onLoad(): void {
        //确保全局只有一个实例
        if (!AudioManager._instance) {
            AudioManager._instance = this;
        } else {
            console.log("AudioManager is already exist");
            this.node.destroy();
        }
        this.audioSource = this.node.getComponent(AudioSource);
    }
    protected onDestroy(): void {
        if(AudioManager.Instance==this){
            AudioManager._instance=null;
            this.node.destroy();
        }
    }
    playBGM(path:string){
        resources.load(path, AudioClip,(err:Error, clip:AudioClip)=>{
            if(err){
                console.log("加载音频失败");
                return;
            }
            if (this.audioSource == null) {
                console.error("audioSource 未初始化");
                return;
            }
            this.audioSource.clip = clip;
            this.audioSource.play();
        });
    }
    playClip(path:string,volume:number=1){
        resources.load(path, AudioClip,(err:Error, clip:AudioClip)=>{
            if(err){
                console.log("加载音频失败");
                return;
            }
            this.audioSource.playOneShot(clip,volume);
        });
    }

}


